package com.yxw.yxnet_cd_center.customer_service.mqtt;

import com.yxw.yxnet_cd_center.common.constant.MqttPrefixConstant;
import com.yxw.yxnet_cd_center.common.enums.NoticeTypeEnum;
import com.yxw.yxnet_cd_center.customer_service.dto.SendDelayNoticeDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.SendNoticeViewDTO;
import com.yxw.yxnet_cd_center.customer_service.service.NoticeService;
import com.yxw.yxnet_cd_center.customer_service.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * mqtt客户端消息处理类
 *
 * @author qlinc
 */
@Slf4j
@Component
public class MqttMessageHandle implements MessageHandler {

    @Autowired
    private NoticeService noticeService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {       
        try {
            String topic = message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC).toString();
            String data = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
            log.info("消息主题:{},收到订阅消息:{},接收的Packet数据{}", topic, message, data);
            if (topic.startsWith(MqttPrefixConstant.MESSAGE_REMINDER_DELAY_TOPIC_CONSUMER)){
                log.info("推送循环提醒消息开始。。。");
                SendNoticeViewDTO dto= JsonUtils.toObject(data,SendNoticeViewDTO.class);
                noticeService.pushCircleNoticeToView(dto);
                log.info("推送循环提醒【"+dto.getType().getTemplateName()+"】消息完成，消息业务bussId参数：{}", dto.getBussId());
            }else if(topic.startsWith(MqttPrefixConstant.THREE_POINTS_UNTREATED_TOPIC_CONSUMER)){
                log.info("三分钟延迟推送消息开始。。。");
                SendDelayNoticeDTO dto= JsonUtils.toObject(data,SendDelayNoticeDTO.class);
                noticeService.delayReminderScenario(dto);
                log.info("三分钟延迟推送【"+dto.getType().getTemplateName()+"】消息完成，消息业务bussId参数：{}", dto.getBussId());
            }
        } catch (Exception e) {
            log.error("mqtt客户端消息处理类异常:{}", e.getStackTrace());
            e.printStackTrace();
        }
    }
}

